package thread.alternate_print;

import java.util.concurrent.Semaphore;

/**
 * 核心是通过信号量的来精准控制每个线程的运行
 * @program: rocsun
 * @description:
 * @author: yx.guo
 * @create: 2025-08-02 15:28
 **/
public class SemaphoreDemo {

    private final int threadCount;
    private int count = 1;
    private final int MAX = 100;
    private Semaphore[] semaphores;

    public SemaphoreDemo(int threadCount) {
        this.threadCount = threadCount;
        // 初始化信号量数组
        semaphores = new Semaphore[threadCount];
        for (int i = 0; i < threadCount; i++) {
            semaphores[i] = new Semaphore(i == 0 ? 1 : 0);
        }
    }

    public void print(int threadIndex) {
        while (count < MAX) {
            try {
                semaphores[threadIndex].acquire(); // 获取信号量，否则阻塞
                if (count > MAX) {
                    // 保证传递，避免死锁
                    releaseNext(threadIndex);
                    return;
                } else {
                    System.out.println(Thread.currentThread().getName() + "-" + count++);
                    releaseNext(threadIndex);
                }
            } catch (InterruptedException e) {
                return;
            }
        }
    }

    /**
     * 释放下一个信号量，进而执行下一个线程
     * @param currentIndex 当前信号量索引
     */
    private void releaseNext(int currentIndex) {
        // 保证传递，避免死锁
        int nextIndex = (currentIndex + 1) % threadCount;
        semaphores[nextIndex].release(); // 释放信号量
    }

    public static void main(String[] args) {
        int threadCount = 3;
        SemaphoreDemo printer = new SemaphoreDemo(threadCount);
        for (int i = 0; i < threadCount; i++) {
            final int threadIndex = i;
            new Thread(() -> printer.print(threadIndex), "t" + (i + 1)).start();
        }
    }

}
